package com.lovo.dao;
import java.sql.*;

public abstract class BaseDAO {
    protected Connection con;
    protected PreparedStatement statement;
    protected ResultSet rs;


    /**
     * 建立一个连接
     */
    public Connection getConnection() {
        // 1. 加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2. 创建连接
            this.con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/lesson3?userSSL=true&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT",
                    "root", "555430");
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return this.con;
    }

    /**
     * 关闭连接(属性)
     */
    public void closeConnection() {
        if (this.rs != null) {
            try {
                this.rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (this.statement != null) {
            try {
                this.statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (this.con != null) {
            try {
                this.con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    /**
     * 关闭连接(连接，SQL执行对象)
     */
    public void closeConnection(Connection con, Statement statement) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    /**
     * 关闭连接(连接，SQL执行对象，结果集)
     */
    public void closeConnection(Connection con, Statement statement, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            closeConnection(con, statement);
        }
    }

    /**
     * 设置自动提交
     * @param autoCommit
     */
    public void setAutoCommit(boolean autoCommit){
        try {
            con.setAutoCommit(autoCommit);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    /**
     * 提交
     */
    public  void commit(){
        try {
            con.commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    /**
     * 回滚
     */
    public void rollback(){
        try {
            con.rollback();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
